const program = require('commander');
const inquirer = require('inquirer');
const { promisify } = require('util');
const path = require('path');
const download = promisify(require('download-git-repo'));
const fs = require('fs-extra');

function createTemplate() {
  program
    .command('create <app-name>')
    .description('create a new project')
    .option('-f, --force', 'overwrite target directory if it exist')
    .action(async (name, options) => {
      const { force } = options;
      const cwd = process.cwd();
      const targetAir = path.join(cwd, name);
      if (fs.existsSync(targetAir)) {
        console.log('有相同路径的文件');
        // 是否为强制创建？
        if (force) {
          await fs.remove(targetAir);
        } else {
          const action = await isOverwrite();
          if (!action) {
            return;
          } else if (action === 'overwrite') {
            // 移除已存在的目录
            console.log(`\r\nRemoving...`);
            try {
              await fs.remove(targetAir);
            } catch (error) {
              console.log(error, '删除文件出错');
            }
          }
        }
      }
      await downloadGitTemplate(targetAir);
    });
}

/**
 * 是否覆盖已存在的目录
 * @returns {Promise<void>}
 */
const isOverwrite = async () => {
  let { action } = await inquirer.prompt([
    {
      name: 'action',
      type: 'list',
      message: '是否强制覆盖？',
      choices: [
        {
          name: 'Overwrite',
          value: 'overwrite',
        },
        {
          name: 'Cancel',
          value: false,
        },
      ],
    },
  ]);
  return action;
};

const downloadGitTemplate = async (targetAir) => {
  try {
    const { vueRepo } = require('../config/repo-config');
    console.log(vueRepo);
    await download(vueRepo, targetAir, { clone: true });
    console.log(`\r\nSuccessfully created project ${chalk.cyan(this.name)}`);
    console.log(`\r\n  cd ${chalk.cyan(this.name)}`);
    console.log('  npm run dev\r\n');
  } catch (error) {
    console.log(error);
  }
};

module.exports = createTemplate;
